package inits

import (
	"ctrip-travel/rpc/global"
	"ctrip-travel/rpc/models/dao"
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"time"
)

var (
	err  error
	once sync.Once
)

func InitApp() {
	viper.SetConfigFile("./config/dev.yaml")
	viper.ReadInConfig()
	viper.Unmarshal(&global.AppConf)
	fmt.Println("动态配置为:", global.AppConf)
}

func InitMysql() {
	app := global.AppConf.MysqlConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", app.User, app.Pass, app.Host, app.Port, app.Database)
	once.Do(func() {
		global.Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	})
	if err != nil {
		fmt.Println("mysql 连接失败", err)
		return
	}
	fmt.Println("mysql 连接成功")
	// 获取通用数据库对象 sql.DB ，然后使用其提供的功能
	sqlDB, _ := global.Db.DB()

	// SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime 设置了连接可复用的最大时间。
	sqlDB.SetConnMaxLifetime(time.Hour)
	global.Db.AutoMigrate(dao.User{}, dao.Vote{}, dao.Order{}, dao.BuyTickets{})
}

type T struct {
	MysqlConfig struct {
		User     string `json:"User"`
		Pass     string `json:"Pass"`
		Host     string `json:"Host"`
		Port     int    `json:"Port"`
		Database string `json:"Database"`
	} `json:"MysqlConfig"`
	RedisConfig struct {
		Host     string `json:"Host"`
		Password string `json:"Password"`
		Db       int    `json:"Db"`
	} `json:"RedisConfig"`
}

var NaCos T

func InitNaCos() {
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.AppConf.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.AppConf.IpAddr,
			ContextPath: "/nacos",
			Port:        global.AppConf.NaCosConfig.Port,
			Scheme:      "http",
		},
	}
	client, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: global.AppConf.DataId,
		Group:  global.AppConf.Group})
	err = json.Unmarshal([]byte(content), &NaCos)

	if err != nil {
		fmt.Println("naCoa 连接失败", err)
		return
	}
	fmt.Println("naCos 连接成功")
	fmt.Println(content)
}
